package com.atguigu.tingshu.user.strategy.impl;
import java.util.Date;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.user.strategy.SaveUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * vip购买，保存购买信息的策略实现类
 */
@Service
@Slf4j
public class UserVipServiceStrategy implements SaveUserPaidRecordStrategy {

    @Autowired
    private UserInfoMapper userInfoMapper ;
    
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper ;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper ;

    @Override
    public void saveUserPaidRecord(UserPaidRecordVo userPaidRecordVo) {

        // 保证接口的幂等性：借助于数据库表的order_no唯一约束
        // 保存vip购买信息
        Long userId = userPaidRecordVo.getUserId();
        String orderNo = userPaidRecordVo.getOrderNo();
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        Long vipServiceConfigId = itemIdList.get(0);
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(vipServiceConfigId);

        UserVipService userVipService = new UserVipService() ;          // 封装要保存的数据
        userVipService.setOrderNo(orderNo);
        userVipService.setUserId(userId);

        /**
         * 如果当前用户是非vip用户，或者是vip用户但是vip过期了，那么开始时间就是当前系统时间
         * 如果当前用户是vip用户，并且没有过期，那么开始时间就应该是vip的过期时间
         */
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Date startTime = new Date() ;
        if(userInfo.getIsVip().equals(1) && userInfo.getVipExpireTime().after(new Date())) {
            startTime = userInfo.getVipExpireTime();
        }
        userVipService.setStartTime(startTime);

        Integer serviceMonth = vipServiceConfig.getServiceMonth();      // 要对日期进行运算可以选择一些日期工具类：Joda-Time ， hutool工具包的日期工具类
        Date date = new DateTime(startTime).plusMonths(serviceMonth).toDate();
        userVipService.setExpireTime(date);
        userVipServiceMapper.insert(userVipService) ;

        // 更改用户的vip的状态
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(date);
        userInfoMapper.updateById(userInfo) ;

    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_VIP;
    }

}
